﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BigLotterySyndicate.Classes;
using SyndicateDAO.DatabaseObject;
using SyndicateBusiness.Classes;

namespace BigLotterySyndicate.Secured
{
    public partial class Default : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Visible)
                return;

            if (!IsUserLoggedIn)
                return;

            SetLists();
        }

        private void SetLists()
        {
            if (Page.IsPostBack)
                return;


            BindNotFinishedDrawsList();

            BindPasswordList();
        }

        private void BindNotFinishedDrawsList()
        {
            var query = this.BusinessFacade.DrawBL.GetAllBySyndicateId(this.LoggedInUser.syndicateId).Where(d=>d.status != "Finished").OrderBy(d=>d.status).OrderByDescending(d => d.drawdate);

            if (query.Count() > 0)
            {
                this.RepeaterDrawsInPlay.DataSource = query;
                this.RepeaterDrawsInPlay.ItemDataBound += new RepeaterItemEventHandler(RepeaterList_ItemDataBound);
                this.RepeaterDrawsInPlay.DataBind();

                this.MultiViewDrawsInPlay.SetActiveView(this.ViewDrawsInPlayList);
                this.ButtonCheckResults.Visible = true;
                this.ButtonUpdateDraws.Visible = true;
                PlaceHolderActions.Visible = true;
            }
            else
            {
                this.MultiViewDrawsInPlay.SetActiveView(this.ViewDrawsInPlayEmpty);
                this.ButtonCheckResults.Visible = false;
                this.ButtonUpdateDraws.Visible = false;
                PlaceHolderActions.Visible = false;
            }
        }

        void RepeaterList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            draw u = e.Item.DataItem as draw;

            BigLotterySyndicate.Secured.Controls.DrawListItem listItem = Utilities.FindControlRecursive(e.Item, "DrawListItem") as BigLotterySyndicate.Secured.Controls.DrawListItem;
            if (listItem != null)
                listItem.Draw = u;
        }

        private void BindPasswordList()
        {
            var query = this.BusinessFacade.FundsLogBL.SelectAllBySyndicateId(this.LoggedInUser.syndicateId).Where(l => l.amount < 0).OrderByDescending(f => f.dateCreated);


            if (query.Count() > 0)
            {
                this.RepeaterPasswords.DataSource = query;
                //this.RepeaterList.ItemDataBound += new RepeaterItemEventHandler(RepeaterList_ItemDataBound);
                this.RepeaterPasswords.DataBind();
                this.PlaceHolderPasswordResets.Visible = true;
            }
            else
            {
                this.PlaceHolderPasswordResets.Visible = false;
            }
        }



        #region print

        protected string PrintTotalDrawsPlayed()
        {
            return this.BusinessFacade.DrawBL.GetAllBySyndicateId(this.LoggedInUser.syndicateId).Where(d => d.status == "Finished").Count().ToString();
        }

        protected string PrintTotalPlayers()
        {
            return this.BusinessFacade.UserBL.GetAllBySyndicateId(this.LoggedInUser.syndicateId).Where(p=>p.isEnabled).Count().ToString();
        }

        protected string PrintMoneySpend()
        {
            int total = 0;

            int linesCount;

            var drawsNotOpen = this.BusinessFacade.DrawBL.GetAllBySyndicateId(this.LoggedInUser.syndicateId).Where(d => d.status != "Open");
        
            foreach(draw item in drawsNotOpen)
            {
                linesCount = this.BusinessFacade.LineBL.SelectAllByDrawId(item.id).Count();
                if ((int)item.pricePerLine == 0)
                {
                    switch (item.type)
                    {
                        case draw.drawType.EUROMILLIONS:
                            total += linesCount*2;
                            break;
                        default:
                            total += linesCount;
                            break;
                    }
                }
                else
                {
                    total += linesCount * (int)item.pricePerLine;
                }
            }

            return String.Format("&pound;{0:0.00}", total);

        }

        protected string PrintMoneyInPlay()
        {
            int total = 0;

            var drawsOpen = this.BusinessFacade.DrawBL.GetAllBySyndicateId(this.LoggedInUser.syndicateId).Where(d => d.status == "Open");

            foreach (draw item in drawsOpen)
            {
                if (item.type == draw.drawType.LOTTO)
                    total += this.BusinessFacade.LineBL.SelectAllByDrawId(item.id).Count();
                else
                    total += (this.BusinessFacade.LineBL.SelectAllByDrawId(item.id).Count() * 2);
            
            }

            return String.Format("&pound;{0:0.00}", total);

        }

        protected string PrintMoneyAvailable()
        {
            var fundsUsers = (double)this.BusinessFacade.UserBL.GetAllBySyndicateId(this.LoggedInUser.syndicateId).Sum(u => u.funds);

            return String.Format("&pound;{0:0.00}", fundsUsers);
        }



        protected string PrintMoneyWon()
        {
            double total = 0;

            var drawsFinished = this.BusinessFacade.DrawBL.GetAllBySyndicateId(this.LoggedInUser.syndicateId).Where(d => d.status == "Finished");

            foreach (draw item in drawsFinished)
            {
                total += item.winnings;

            }

            return String.Format("&pound;{0:0.00}", total);

            }
        protected string PrintUserName(object data)
        {
            fundsLog u = data as fundsLog;

            String password = PrintUserTempPassword(data);

            password = System.Text.RegularExpressions.Regex.Replace(password, "<b>", "");
            password = System.Text.RegularExpressions.Regex.Replace(password, "</b>", "");
            password = password.Split('(')[0].Trim();
            String body = "Hello, Please use the password: " + password + " and your company email address to log in and set up your syndicate account. The website url is: http://syndicates.biggroup.co.uk";

            

            return String.Format("{0} <a href=\"mailto:{1}?subject=Your temporary syndicate password.&body={2}\">{1}</a>", u.user1.username, u.user1.email,Page.Server.UrlDecode(body));
        }

        protected string PrintUserTempPassword(object data)
        {
            fundsLog u = data as fundsLog;

            string password = u.description.Split(':')[1];

            if(password.TrimStart().StartsWith("S"))
                return String.Format("<b>{0}</b> (new account)", password);
            else
                return String.Format("<b>{0}</b> (password reset)", password);

        }

        #endregion

        protected void ButtonCheckResults_Click(object sender, EventArgs e)
        {
            this.BusinessFacade.ResultBL.FindResults(this.LoggedInUser.syndicateId);

            InsertEventLogEntry("Results check Lotto.");

            this.BusinessFacade.ResultBL.FindResults(this.LoggedInUser.syndicateId,draw.drawType.EUROMILLIONS);

            InsertEventLogEntry("Results check EuroMillions.");

            this.BusinessFacade.ResultBL.FindResults(this.LoggedInUser.syndicateId, draw.drawType.HEALTHLOTTERY);

            InsertEventLogEntry("Results check HealtLottery.");

            this.Redirect("/Secured/Default.aspx?Ns=0");
        }

        protected void ButtonUpdateDraws_Click(object sender, EventArgs e)
        {
            UpdateDraws();

            this.Redirect("/Secured/Default.aspx?Ns=0");
        }

        private void UpdateDraws()
        {
            var pendingDraws = this.BusinessFacade.DrawBL.GetAllBySyndicateId(this.LoggedInUser.syndicateId).Where(d=>d.status == draw.drawstatus.OPEN);

            foreach (draw item in pendingDraws)
            {
                if (item.drawdate.AddHours(-1) < DateTime.Now)
                {
                    item.status = draw.drawstatus.PENDING;
                }                
            }
            this.BusinessFacade.DrawBL.UpdateDraw();

            InsertEventLogEntry("Draws update.");

        }
    }
}